package com.ai.bitcoin.service.impl;

import com.ai.bitcoin.constant.CodeConstant;
import com.ai.bitcoin.jpa.dao.ExtraRedeemCodeDao;
import com.ai.bitcoin.jpa.entity.BccUser;
import com.ai.bitcoin.jpa.entity.ExtraRedeemCode;
import com.ai.bitcoin.output.GeneralReponse;
import com.ai.bitcoin.service.ExtraRedeemCodeService;
import com.ai.bitcoin.service.helper.ExtraRedeemServiceHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Service
@Slf4j
public class ExtraRedeemCodeServiceImpl implements ExtraRedeemCodeService {

    @Autowired
    private ExtraRedeemCodeDao extraRedeemCodeDao;

    @Autowired
    private ExtraRedeemServiceHelper extraRedeemServiceHelper;


    @Override
    public GeneralReponse getOne(BccUser bccUser) {
        //查询该用户是否已经获取过兑换码
        List<ExtraRedeemCode> extraRedeemCodeList = extraRedeemCodeDao.findByUserOpenIdAndAndIsActive(bccUser.getOpenId(),1);
        if(!CollectionUtils.isEmpty(extraRedeemCodeList)){
            return new GeneralReponse(CodeConstant.CODE_HAS_BEEN_GET,null,"你已经获取过兑换码，请勿重复获取！");
        }
        //查询可获取的兑换码
        ExtraRedeemCode extraRedeemCode = extraRedeemCodeDao.getOneActive();
        if(extraRedeemCode == null){
            return new GeneralReponse(CodeConstant.CODE_HAS_BEEN_FINISHED,null,"兑换码已领完！");
        }
        //更换兑换码状态
        int i = extraRedeemServiceHelper.updateOne(bccUser.getOpenId(),extraRedeemCode.getId());
        if(i!=1){
            return new GeneralReponse(CodeConstant.BUSINESS_ERROR,null,"获取失败，请稍后再试！");
        }
        // //返回相应的兑换码
        // List<ExtraRedeemCode> result = extraRedeemCodeDao.findByUserOpenIdAndAndIsActive(bccUser.getOpenId(),1);
        // if(CollectionUtils.isEmpty(extraRedeemCodeList)){
        //     return new GeneralReponse(CodeConstant.BUSINESS_ERROR,null,"获取失败，请稍后再试！");
        // }
        String code = extraRedeemCode.getCode();
        return new GeneralReponse(CodeConstant.SUCCESS,code);
    }
}
